package com.yxinsur.imc.business.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.ArrayList;
import java.util.List;

import com.yxinsur.imc.business.domain.ImcTenant;
import com.yxinsur.imc.business.enums.IsDeletedEnum;
import com.yxinsur.imc.business.events.publisher.SysOrgCreateEventPublisher;
import com.yxinsur.imc.business.events.publisher.TenantCreateEventPublisher;
import com.yxinsur.imc.business.form.TenantForm;
import com.yxinsur.imc.business.form.TenantUserForm;
import com.yxinsur.imc.business.listener.BusinessMqMessageListener;
import com.yxinsur.imc.business.mapper.ImcTenantMapper;
import com.yxinsur.imc.business.service.IImcTenantService;
import com.yxinsur.imc.common.exception.BusinessException;
import com.yxinsur.imc.common.rocketMq.entity.PantheonChannel;
import com.yxinsur.imc.business.vo.TenantVo;
import com.yxinsur.imc.common.core.domain.entity.SysOrg;
import com.yxinsur.imc.common.core.domain.entity.SysUser;
import com.yxinsur.imc.common.utils.SecurityUtils;
import com.yxinsur.imc.common.utils.StringUtils;
import com.yxinsur.imc.system.domain.SysRoleOrg;
import com.yxinsur.imc.system.domain.SysUserRole;
import com.yxinsur.imc.system.mapper.SysOrgMapper;
import com.yxinsur.imc.system.mapper.SysRoleOrgMapper;
import com.yxinsur.imc.system.mapper.SysUserMapper;
import com.yxinsur.imc.system.mapper.SysUserRoleMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


/**
 * 租户Service业务层处理
 *
 * @author imc
 * @date 2021-03-26
 */
@Service
public class ImcTenantServiceImpl extends ServiceImpl<ImcTenantMapper, ImcTenant> implements IImcTenantService
{
    @Autowired
    private ImcTenantMapper imcTenantMapper;
    @Autowired
    private SysOrgMapper sysOrgMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysRoleOrgMapper sysRoleOrgMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private TenantCreateEventPublisher tenantCreateEventPublisher;
    @Autowired
    private SysOrgCreateEventPublisher sysOrgCreateEventPublisher;

    @Value("${pantheon.channelUrl}")
    private String pantheonChannelUrl;

    /**
     * 查询租户
     *
     * @param id 租户ID
     * @return 租户
     */
    @Override
    public ImcTenant selectImcTenantById(Long id)
    {
        return imcTenantMapper.selectImcTenantById(id);
    }

    /**
     * 查询租户列表
     *
     * @param imcTenant 租户
     * @return 租户
     */
    @Override
    public List<TenantVo> selectImcTenantList(TenantForm imcTenant)
    {
        return imcTenantMapper.selectImcTenantList(imcTenant);
    }

    /**
     * 新增租户
     *
     * @param tenantSaveForm 租户
     * @return 结果
     */
    @Transactional
    @Override
    public int insertImcTenant(TenantForm tenantSaveForm)
    {
        //租户信息保存
        ImcTenant imcTenant = new ImcTenant();
        BeanUtils.copyProperties(tenantSaveForm,imcTenant);
        //调用远程渠道新增接口
        //pantheonChannelAdd(imcTenant);
        imcTenantMapper.insertImcTenant(imcTenant);
        Long tenantId = imcTenant.getId();
        //部门信息保存
        SysOrg sysOrgRoot = new SysOrg();
        sysOrgRoot.setParentId(0L);
        sysOrgRoot.setAncestors("0");
        sysOrgRoot.setOrgName(tenantSaveForm.getCompanyName());
        sysOrgRoot.setOrderNum("0");
        sysOrgRoot.setTenantId(tenantId);
        sysOrgRoot.setOrgGuid(imcTenant.getTenantGuid());
        sysOrgMapper.insertOrg(sysOrgRoot);
        tenantCreateEventPublisher.pushlish("租户信息录入成功",imcTenant);
        sysOrgCreateEventPublisher.pushlish("组织信息录入成功",sysOrgRoot);
        return 1;
    }

    /**
     * 访问云服环境获得租户的guid
     * @param imcTenant
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void pantheonChannelAdd(ImcTenant imcTenant) {
        PantheonChannel pantheonChannel = new PantheonChannel();
        pantheonChannel.setChannelName(imcTenant.getCompanyName());
        pantheonChannel.setChannelSimpleName(imcTenant.getCompanyShortName());
        pantheonChannel.setBusinessLicense(imcTenant.getBizLicenseCode());
        pantheonChannel.setBusinessLicenseCode(imcTenant.getAgencyCode());
        pantheonChannel.setLogo(imcTenant.getLogo());
        pantheonChannel.setChannelSource("2");
        String json = JSON.toJSONString(pantheonChannel);
        log.debug("新增云服渠道信息参数"+json);
        String returnJson = HttpUtil.post(pantheonChannelUrl+"/ocesnus/channel/add",json);
        log.debug("新增云服渠道信息返回结果:"+returnJson);
        if(StringUtils.isEmpty(returnJson)){
           throw new BusinessException("新增云服渠道信息错误");
        }
        JSONObject result = JSONObject.parseObject(returnJson);
        if(result!=null && result.getIntValue("code")==10000){
            imcTenant.setTenantGuid(result.getString("channelNo"));
        }else{
            throw new BusinessException("新增云服渠道信息错误");
        }
    }

    @Transactional
    @Override
    public int insertImcTenantUser(TenantUserForm tenantUserForm)
    {
        Long tenantId = tenantUserForm.getTenantId();
        SysOrg sysOrg = sysOrgMapper.getByTenantId(tenantId);
        //用户信息保存
        SysUser sysUser = new SysUser();
        sysUser.setOrgId(sysOrg.getOrgId());
        sysUser.setUserName(tenantUserForm.getUserName());
        sysUser.setNickName(tenantUserForm.getNickName());
        sysUser.setEmail(tenantUserForm.getEmail());
        sysUser.setPhonenumber(tenantUserForm.getPhonenumber());
        sysUser.setSex(tenantUserForm.getSex());
        sysUser.setPassword(SecurityUtils.encryptPassword(tenantUserForm.getPassword()));
        sysUser.setTenantId(tenantId);
        sysUserMapper.insertUser(sysUser);
        //角色-用户   角色-机构
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setRoleId(102L);
        sysUserRole.setUserId(sysUser.getUserId());
        ArrayList<SysUserRole> sysUserRoles = new ArrayList<>();
        sysUserRoles.add(sysUserRole);
        sysUserRoleMapper.batchUserRole(sysUserRoles);
        SysRoleOrg sysRoleOrg = new SysRoleOrg();
        sysRoleOrg.setRoleId(102L);
        sysRoleOrg.setOrgId(sysOrg.getOrgId());
        ArrayList<SysRoleOrg> sysRoleOrgs = new ArrayList<>();
        sysRoleOrgs.add(sysRoleOrg);
        sysRoleOrgMapper.batchRoleOrg(sysRoleOrgs);
        return 1;
    }

    /**
     * 修改租户
     *
     * @param tenantForm 租户
     * @return 结果
     */
    @Transactional
    @Override
    public int updateImcTenant(TenantForm tenantForm)
    {
        ImcTenant imcTenant = new ImcTenant();
        BeanUtils.copyProperties(tenantForm,imcTenant);
        //修改云服渠道信息
        //pantheonChannelUpdate(imcTenant);
        imcTenantMapper.updateImcTenant(imcTenant);
        Long tenantId = imcTenant.getId();
        SysOrg sysOrg = sysOrgMapper.getByTenantId(tenantId);
        sysOrg.setOrgName(imcTenant.getCompanyName());
        sysOrgMapper.updateOrg(sysOrg);
        tenantCreateEventPublisher.pushlish("租户信息修改成功",imcTenant);
        return 1;
    }

    /**
     * 云服渠道信息修改
     * @param imcTenant
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void pantheonChannelUpdate(ImcTenant imcTenant) {
        ImcTenant tenant = imcTenantMapper.selectImcTenantById(imcTenant.getId());
        PantheonChannel pantheonChannel = new PantheonChannel();
        pantheonChannel.setChannelName(imcTenant.getCompanyName());
        pantheonChannel.setChannelSimpleName(imcTenant.getCompanyShortName());
        pantheonChannel.setBusinessLicenseCode(imcTenant.getAgencyCode());
        pantheonChannel.setBusinessLicense(imcTenant.getBizLicenseCode());
        pantheonChannel.setChannelNo(tenant.getTenantGuid());
        pantheonChannel.setChannelSource("2");
        String json = JSON.toJSONString(pantheonChannel);
        log.debug("修改云服渠道信息参数:"+json);
        String returnJson = HttpUtil.post(pantheonChannelUrl+"/ocesnus/channel/update",json);
        log.debug("修改云服渠道信息返回结果:"+returnJson);
        if(StringUtils.isEmpty(returnJson)){
            throw new BusinessException("修改云服渠道信息错误");
        }
        JSONObject result = JSONObject.parseObject(returnJson);
        if(result==null || result.getIntValue("code")!=10000){
            throw new BusinessException("修改云服渠道信息错误");
        }
    }

    /**
     * 批量删除租户
     *
     * @param ids 需要删除的租户ID
     * @return 结果
     */
    @Override
    public int deleteImcTenantByIds(String[] ids)
    {
        return imcTenantMapper.deleteImcTenantByIds(ids);
    }

    /**
     * 删除租户信息
     *
     * @param id 租户ID
     * @return 结果
     */
    @Override
    public int deleteImcTenantById(String id)
    {
        return imcTenantMapper.deleteImcTenantById(id);
    }

    @Override
    public List<SysUser> selectUserList(SysUser user) {
        return userMapper.selectUserList4tenantId(user);
    }

    /**
     * 新增消息队列中的渠道信息
     * @param channels
     * @return
     */
    @Override
    public int addPantheon(List<PantheonChannel> channels) {
        int count = 0;
        for (PantheonChannel channel : channels) {
            ImcTenant imcTenant = new ImcTenant();
            imcTenant.setCompanyName(channel.getChannelName());
            imcTenant.setCompanyShortName(channel.getChannelSimpleName());
            imcTenant.setBizLicenseCode(channel.getBusinessLicense());
            imcTenant.setAgencyCode(channel.getBusinessLicenseCode());
            imcTenant.setTenantGuid(channel.getChannelNo());
            imcTenant.setIsDeleted(IsDeletedEnum.N.getCode());
            imcTenant.setCreateId("rocketmq");
            imcTenant.setUpdateId("rocketmq");
            count  += imcTenantMapper.insertImcTenant(imcTenant);
        }
        return count;
    }

    /**
     * 修改消息队列中的渠道信息
     * @param channels
     * @return
     */
    @Override
    public int updatePantheon(List<PantheonChannel> channels) {
        int count = 0;
        for (PantheonChannel channel : channels) {
            ImcTenant imcTenant = new ImcTenant();
            imcTenant.setCompanyName(channel.getChannelName());
            imcTenant.setCompanyShortName(channel.getChannelSimpleName());
            imcTenant.setBizLicenseCode(channel.getBusinessLicense());
            imcTenant.setAgencyCode(channel.getBusinessLicenseCode());
            UpdateWrapper<ImcTenant> wrapper = new UpdateWrapper<>();
            wrapper.eq("tenant_guid",channel.getChannelNo());
            wrapper.eq("is_deleted",IsDeletedEnum.N.getCode());
            count  += imcTenantMapper.update(imcTenant,wrapper);
        }
        return count;
    }

    /**
     * 删除消息队列中的渠道信息
     * @param channels
     * @return
     */
    @Override
    public int deletePantheon(List<PantheonChannel> channels) {
        int count = 0;
        for (PantheonChannel channel : channels) {
            QueryWrapper<ImcTenant> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("tenant_guid",channel.getChannelNo());
            ImcTenant imcTenant = imcTenantMapper.selectOne(queryWrapper);
            imcTenant.setIsDeleted(String.valueOf(imcTenant.getId()));
            count  += imcTenantMapper.updateById(imcTenant);
        }
        return count;
    }
}
